package com.liugh.util;


import cn.hutool.core.io.FileUtil;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.IOException;

/**
 * 一些操作PDF有关的工具类
 */
public class PDFUtil {

    /**
     * 解析PDF的内容为string,PDF内容不能加密
     *
//     * @param filePath 本地文件存储目录
     * @return
     */
//    public static String pdfToString(String filePath) throws MalformedURLException {
//        File file = new File(filePath);
//        return readPDFToString(file);
//    }


    /**
     * 读取PDF的内容
     * @param file
     * @return string
     * @throws IOException
     */
    private static String readPDFToString(File file) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        PDFParser pdfParser = new PDFParser(new RandomAccessFile(file, "r"));
        pdfParser.parse();
        try (PDDocument pdDocument = new PDDocument(pdfParser.getDocument())) {
            PDFTextStripper pdfTextStripper = new PDFTextStripper();
            stringBuilder.append(pdfTextStripper.getText(pdDocument));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 中车公司全文检索，从url中获取资源
     * @param filePath  文件URL
     * @param storgPath  文件暂存在本地的位置
     * @return
     * @throws IOException .
     */
    public static String pdfToStringUrl(String filePath,String storgPath) throws IOException {
        String filestore = LiughFileUtil.getFileFromUrl(filePath,storgPath,filePath.substring(filePath.lastIndexOf("/"),filePath.length()-1));
        String content = readPDFToString(FileUtil.file(filestore));
        FileUtil.del(storgPath);
        return content;
    }
}
